/*
 * @Author: Eureka 
 * @Date: 2022-01-19 11:46:56 
 * @Last Modified by: Eureka
 * @Last Modified time: 2022-01-21 11:44:57
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:senkoo_platform/Utils/base_standard.dart';
import 'package:senkoo_platform/Utils/base_text.dart';
import 'package:senkoo_platform/Utils/set_edge_insets.dart';
import 'package:senkoo_platform/base_message/sp_constanst.dart';
import 'package:senkoo_platform/base_router/base_router_util.dart';
import 'package:senkoo_platform/config/config.dart';
import 'package:senkoo_platform/iconfont/iconfont.dart';
import 'package:senkoo_platform/views/login_modular/login_page.dart';
import 'package:sp_util/sp_util.dart';

class LimitsAuthorityPage extends StatefulWidget {
  LimitsAuthorityPage({Key? key}) : super(key: key);

  @override
  _LimitsAuthorityPageState createState() {
    return _LimitsAuthorityPageState();
  }
}

class _LimitsAuthorityPageState extends State<LimitsAuthorityPage> {
  bool _touchbutton = false;
  String _buttonString = "同意并开启以上权限";

  final List<AuthItem> _authList = [
    AuthItem(
        name: '定位权限',
        info: '提供精确的定位',
        permission: Permission.location,
        icon: IconFont.iconguidepageposition,
        isAllow: 0),
    AuthItem(
        name: '相机权限',
        info: '用于拍摄现场施工图或视频',
        permission: Permission.camera,
        icon: IconFont.iconguidepagecamera,
        isAllow: 0),
    AuthItem(
        name: '相册权限',
        info: '使用本地图片上传施工图、签收单等',
        permission: Permission.photos,
        icon: IconFont.iconguidepagephotographalbum,
        isAllow: 0),
  ];

  @override
  void initState() {
    if (AppConfig.isAndroid) {
      _authList.add(AuthItem(
          name: '文件权限',
          info: '保存或下载我们的指导图册',
          permission: Permission.storage,
          icon: IconFont.wenjianjia,
          isAllow: 0));
    }

    _authStatus();

    super.initState();
  }

  Future<void> _authStatus() async {
    await Future.forEach(_authList, (AuthItem item) async {
      final _permissions = item.permission;
      var status = await _permissions.status;
      if (status != PermissionStatus.denied) {
        if (status == PermissionStatus.permanentlyDenied ||
            status == PermissionStatus.limited) {
          item.isAllow = 2;
        } else if (status == PermissionStatus.granted) {
          item.isAllow = 1;
        }
      }
    });

    if (_authList.where((item) => item.isAllow == 2).isNotEmpty) {
      //说明有不同意的权限
      _touchbutton = true;
      _buttonString = "手动开启权限";
    } else if (_authList.where((item) => item.isAllow == 1).length ==
        _authList.length) {
      _touchbutton = true;
      _buttonString = "立即进入";
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => Container(
        margin: setEdgeInsets(bottom: 50),
        color: Standard.colorFAFAFA,
        child: SafeArea(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: setSymEdgeInsets(horizontal: 34, vertical: 30),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    text(
                        textString: '欢迎使用${AppConfig.appName}！',
                        textColor: Standard.color333333,
                        textSize: 21.sp,
                        textWeight: semibold),
                    Padding(
                      padding: setEdgeInsets(top: 14, bottom: 8),
                      child: text(
                          textString: '为了提供更优秀的工作体验',
                          textColor: Standard.color666666,
                          textSize: 16.sp),
                    ),
                    textSpanRich(children: [
                      textSpan(
                          textString: '部分功能需要您',
                          textColor: Standard.color666666,
                          textSize: 16.sp),
                      textSpan(
                          textString: '「开启」',
                          textColor: Standard.color333333,
                          textSize: 16.sp,
                          textWeight: semibold),
                      textSpan(
                          textString: '以下权限',
                          textColor: Standard.color666666,
                          textSize: 16.sp),
                    ])
                  ],
                ),
              ),
              Expanded(
                  child: SingleChildScrollView(
                child: Column(
                  children: _authListWidget(),
                ),
              )),
              Padding(
                padding: setSymEdgeInsets(horizontal: 35),
                child: Column(
                  children: [
                    Container(
                      width: 306.w,
                      margin: setEdgeInsets(bottom: 25),
                      child: textRich(
                          textString:
                              '此选项为核心业务必要功能，如无授权将无法正常使用我们的app。您可以在系统设置中关闭以上权限。',
                          maxLine: 3,
                          textColor: Standard.color999999,
                          textSize: 12.sp),
                    ),
                    Padding(padding: setEdgeInsets()),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          height: 40.h,
                          decoration: BoxDecoration(
                              border: Border.all(
                                  width: 1.w, color: Standard.color979797),
                              borderRadius: Standard.baseBorderRadius20),
                          padding: setEdgeInsets(),
                          child: _AuthButton(
                            textString: '不同意',
                            color: Standard.colorFFFFFF,
                            disabledColor: Standard.colorFFFFFF,
                            textColor: Standard.color333333,
                            onPressed: () async {
                              // final result = await baseShowOkCancelAlertDialog(
                              //   context: context,
                              //   title: "提示",
                              //   message: "后续操作中，需要这些权限，\n确定继续操作吗",
                              //   okLabel: "直接进入",
                              //   cancelLabel: "去授权",
                              // );
                              // if (result == OkCancelResult.ok) {
                              //   SpUtil.putBool(SpConstanst.keyGuide, true);
                              //   _goLogin();
                              // }
                            },
                          ),
                        ),
                        Container(
                          constraints: BoxConstraints(minWidth: 180.w),
                          child: _AuthButton(
                            textString: _buttonString,
                            color: Standard.colorFAAD14,
                            disabledColor: Standard.colorFAAD14,
                            textColor: Standard.colorFFFFFF,
                            onPressed: () async {
                              if (!_touchbutton) {
                                List<Permission> _permissionList = [];
                                _authList.asMap().forEach((index, item) {
                                  _permissionList.add(item.permission);
                                });
                                Map<Permission, PermissionStatus> statuses =
                                    await _permissionList.request();
                                _authList.asMap().forEach((index, item) {
                                  if (statuses[item.permission] ==
                                          PermissionStatus.permanentlyDenied ||
                                      statuses[item.permission] ==
                                          PermissionStatus.limited) {
                                    _authList[index].isAllow = 2;
                                  } else if (statuses[item.permission] ==
                                      PermissionStatus.granted) {
                                    _authList[index].isAllow = 1;
                                  }

                                  _touchbutton = true;
                                });
                                if (_authList
                                    .where((item) => item.isAllow == 2)
                                    .isNotEmpty) {
                                  //说明有不同意的权限
                                  _buttonString = "手动开启权限";
                                } else if (_authList
                                        .where((item) => item.isAllow == 1)
                                        .length ==
                                    _authList.length) {
                                  _buttonString = "立即进入";
                                }
                              } else {
                                if (_buttonString == "手动开启权限") {
                                  openAppSettings();
                                } else {
                                  SpUtil.putBool(SpConstanst.keyGuide, true);
                                  _goLogin();
                                }
                              }
                              setState(() {});
                            },
                          ),
                        )
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      );

  Future<void> _goLogin() async =>
      RouterUtil.pushRemovePage(context, LoginPage());

  List<Widget> _authListWidget() {
    List<Widget> _list = [];
    _authList.asMap().forEach((index, item) {
      _list.add(GestureDetector(
        onTap: () async {
          final _permissions = item.permission;
          var status = await _permissions.status;
          if (status == PermissionStatus.permanentlyDenied ||
              status == PermissionStatus.limited) {
            // final result = await baseShowOkCancelAlertDialog(
            //   context: context,
            //   title: "提示",
            //   message: "是否手动开启该权限",
            //   okLabel: "确定",
            //   cancelLabel: "取消",
            // );
            // if (result == OkCancelResult.ok) {
            //   openAppSettings();
            // }
          } else {
            //没有被禁止 或 未知的情况
            Map<Permission, PermissionStatus> statuses =
                await [item.permission].request();
            if (statuses[item.permission] ==
                PermissionStatus.permanentlyDenied) {
              _authList[index].isAllow = 2;
            } else if (statuses[item.permission] == PermissionStatus.granted) {
              _authList[index].isAllow = 1;
            }
          }
          setState(() {});
        },
        child: Container(
          margin: setEdgeInsets(left: 18, right: 18, bottom: 18),
          padding: setSymEdgeInsets(horizontal: 18, vertical: 14),
          decoration: BoxDecoration(
              color: Standard.colorFFFFFF,
              borderRadius: Standard.baseBorderRadius8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    width: 26.w,
                    height: 26.w,
                    child: Icon(
                      item.icon,
                      color: Standard.colorFAAD14,
                      size: 26.w,
                    ),
                    margin: setEdgeInsets(right: 20),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      text(
                          textString: item.name,
                          textColor: Standard.color333333,
                          textSize: 18.sp,
                          textWeight: semibold),
                      Container(
                        child: textRich(
                            textString: item.info,
                            textColor: Standard.color999999,
                            textSize: 14.sp),
                      )
                    ],
                  ),
                ],
              ),
              // Offstage(
              //   offstage: item.isAllow == 0,
              //   child: DotIndicator(
              //     size: 20.w,
              //     color: item.isAllow == 1
              //         ? Standard.colorFAAD14
              //         : Standard.colorDC3A25,
              //     child: Icon(
              //       item.isAllow == 1 ? Icons.check : Icons.close,
              //       color: Standard.colorFFFFFF,
              //       size: 14.w,
              //     ),
              //   ),
              // )
            ],
          ),
        ),
      ));
    });
    return _list;
  }
}

class _AuthButton extends StatelessWidget {
  const _AuthButton({
    Key? key,
    this.textString = "",
    this.color,
    this.disabledColor,
    this.textColor,
    this.onPressed,
  }) : super(key: key);

  final String textString;
  final VoidCallback? onPressed;
  final dynamic color;
  final dynamic disabledColor;
  final dynamic textColor;
  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      shape: RoundedRectangleBorder(borderRadius: Standard.baseBorderRadius20),
      disabledColor: disabledColor,
      color: color,
      animationDuration: const Duration(seconds: 0),
      onPressed: onPressed,
      elevation: 0,
      highlightElevation: 2,
      height: 40.h,
      padding: setEdgeInsets(),
      child: Padding(
        padding: setSymEdgeInsets(vertical: 8, horizontal: 26),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            text(textString: textString, textColor: textColor, textSize: 14.sp)
          ],
        ),
      ),
    );
  }
}

class AuthItem {
  String name;
  String info;
  Permission permission;
  IconData icon;
  int isAllow; //isAllow 0 未知 1 允许 2 不允许
  AuthItem(
      {required this.name,
      required this.info,
      required this.permission,
      required this.icon,
      required this.isAllow});
}
